package com.tcfvic.server.persistance;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private final SessionFactory sessionFactory;
	private static HibernateUtil instance = new HibernateUtil();
	private static final Object o = new Object();

	public HibernateUtil() {
		sessionFactory = createSessionFactory();
	}

	public static Session getSession() {
		if (instance == null) {
			synchronized (o) {
				if (instance == null) {
					instance = new HibernateUtil();
				}
			}
		}
		Session session = instance.sessionFactory.openSession();
		if (session == null || !session.isOpen()) {
			session = instance.sessionFactory.openSession();
		}
		
		return session;
	}

	private SessionFactory createSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
}
